# Maintainer: Alexey Kasatkin <alexeikasatkin@gmail.com>
# ArchLinux maintainer: Jaroslav Lichtblau <dragonlord@aur.archlinux.org>
# Contributor: Brian Galey <bkgaley at gmail dot com>
# Contributor: Pietro Zambelli <peter.zamb at gmail dot com>

_realname=libspatialite
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=5.0.1
pkgrel=4
pkgdesc="SQLite extension to support spatial data types and operations (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32')
url="https://www.gaia-gis.it/fossil/libspatialite/index"
license=('MPL' 'GPL' 'LGPL')
makedepends=("${MINGW_PACKAGE_PREFIX}-autotools" "${MINGW_PACKAGE_PREFIX}-cc")
depends=("${MINGW_PACKAGE_PREFIX}-geos"
         "${MINGW_PACKAGE_PREFIX}-librttopo"
         "${MINGW_PACKAGE_PREFIX}-libfreexl"
         "${MINGW_PACKAGE_PREFIX}-libxml2"
         "${MINGW_PACKAGE_PREFIX}-minizip"
         "${MINGW_PACKAGE_PREFIX}-proj"
         "${MINGW_PACKAGE_PREFIX}-sqlite3"
         "${MINGW_PACKAGE_PREFIX}-libiconv")
options=('strip')
source=("https://www.gaia-gis.it/gaia-sins/${_realname}-${pkgver}.tar.gz"
        "01-fix-pkgconfig.patch"
        "0002-use-win32-mutex-locks.patch"
        "0003-headers-gaiaconfig-remove-triplet.patch")
sha256sums=('eecbc94311c78012d059ebc0fae86ea5ef6eecb13303e6e82b3753c1b3409e98'
            '6635724e88dc5f840e3b3df2a236ae8f8a61321f5c78fd7f382008009c9a2a65'
            '66aeb63f0909fd5f2435d52b131e5832f84c0e3cf57f827b836bfde70425803e'
            '416ac9850d877012cc0f8968703f45ada4fec8ca7adc96dbc49fa339041609e3')

prepare() {
  cd "${srcdir}/${_realname}-${pkgver}"
  sed -i configure.ac -e "s|mingw32|${MINGW_CHOST}|g"
  patch -p1 -i "${srcdir}/01-fix-pkgconfig.patch"
  patch -p1 -i "${srcdir}/0002-use-win32-mutex-locks.patch"
  patch -p1 -i "${srcdir}/0003-headers-gaiaconfig-remove-triplet.patch"

  # autoreconf to get libtool files with clang support
  autoreconf -fiv
}

build() {
  [[ -d "${srcdir}"/build-${MINGW_CHOST} ]] && rm -rf "${srcdir}"/build-${MINGW_CHOST}
  mkdir -p "${srcdir}/build-${MINGW_CHOST}" && cd "${srcdir}/build-${MINGW_CHOST}"
  
  ../${_realname}-${pkgver}/configure \
    --host=${MINGW_CHOST} \
    --target=${MINGW_CHOST} \
    --build=${MINGW_CHOST} \
    --prefix=${MINGW_PREFIX} \
    --enable-rttopo \
    --enable-libxml2

  make
}

package() {
  cd "${srcdir}/build-${MINGW_CHOST}"
  make DESTDIR="${pkgdir}" install
  # Fix mod_spatialite location to be possible: SELECT load_extension('mod_spatialite');
  mv "${pkgdir}${MINGW_PREFIX}/lib/mod_spatialite.dll" "${pkgdir}${MINGW_PREFIX}/bin/"

  local PREFIX_WIN=$(cygpath -wm ${MINGW_PREFIX})
  for pcfile in "${pkgdir}${MINGW_PREFIX}"/lib/pkgconfig/*.pc; do
    sed -s "s|${PREFIX_WIN}|${MINGW_PREFIX}|g" -i "${pcfile}"
  done
}
